package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    //用户预约信息数据提交
    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map) {
        //1 获取前台用户的手机号
        String telephone = (String) map.get("telephone");

        /*
         * 2 根据前台用户手机号+RedisConstant.SENDTYPE_ORDER
         *   获取redis中缓存的系统生成的验证码
         * */
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        //3 获取前台用户输入的验证码
        String validateCode = (String) map.get("validateCode");

        //4 校验用户输入的验证码和系统短信发送的是否一致

        //4.1 如果失败返回错误结果,并结束方法执行
        if (!(codeInRedis != null && validateCode != null && codeInRedis.equals(validateCode))) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Result result = null;

        //4.2 如果输入的验证码与系统生成一致
        try {
            //4.3 向集合中添加预约类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            //调用体检预约服务
            result = orderService.submitOrder(map);

            //预约成功,发送短信通知
            if (result.isFlag()) {
                //获取预约日期
                String orderDate = (String) map.get("orderDate");
                //发送预约成功的短信提示
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
            }
        } catch (ClientException c) {
            c.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDER_FAIL);
        }
        return result;

    }

    //根据orderId查询 体检人姓名 体检日期 体检套餐 体检预约类型
    @RequestMapping("/findByOrderId")
    public Result findByOrderId(Integer orderId) {
        try {
            Map map = orderService.findByOrderId(orderId);
            //查询预约信息成功
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            //查询预约信息失败
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL); }
        }
    }
